<template>
  <div style="width: 100%;height: calc(100vh - 113px)" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from '@/components/Mixins/resize'
import { getCompanyId } from '@/util/storage'
import {
  getBelongDeviceList
} from '@/api/iot/iotDeviceBelongApi'
import { listUser } from '@/api/auth/authUserApi'
export default {
  name: 'BelongAnalysis',
  mixins: [resize],
  data() {
    return {
      userList: [],
      chartData: {},
      companyId: getCompanyId()
    }
  },
  mounted() {
    this.getAllUser()
  },
  methods: {
    getAllDeviceBelong() {
      this.chartData = {
        'name': '',
        'children': []
      }
      let userSize = 0
      this.userList.forEach(user => {
        if (user.userName === 'root' || user.userName === 'testZHM') {
          return
        }
        if (userSize > 10) {
          return
        }
        userSize = userSize + 1
        getBelongDeviceList({
          userId: user.userId
        }).then(res => {
          const { code, data } = res
          if (code === '200') {
            const belongData = {
              'name': user.userName,
              'children': []
            }
            const belongList = data
            belongList.forEach(belong => {
              belongData['children'].push({
                'name': belong.deviceName + '(' + belong.deviceCore + ')'
              })
            })
            this.chartData['children'].push(belongData)
            this.initChart()
          }
        })
      })
    },
    getAllUser() {
      listUser({
        companyId: this.companyId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.userList = data
          this.getAllDeviceBelong()
        }
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        series: [
          {
            type: 'tree',
            name: this.$t('param'),
            data: [this.chartData],
            top: '0',
            bottom: '0',
            right: '20%',
            left: '13px',
            symbolSize: 5,
            initialTreeDepth: 4,
            label: {
              position: 'left',
              verticalAlign: 'middle',
              align: 'right',
              fontSize: 10
            },
            leaves: {
              label: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
              }
            },
            expandAndCollapse: true
          }
        ]
      })
    }
  }
}
</script>
